import React, { useState, useEffect } from 'react';
import { useDispatch, connect } from 'umi';
import { message, Modal, Table, Button, Input, Row, Col } from 'antd';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import styles from './index.less';
import { columns } from '../RoleAuthUsers/userConfig';

const UsersSelect = (props) => {
  const { isModalVisible = false, handleCancel, handOk, selectUsers, common } = props;
  const { appCodeOfSelect } = common;
  const dispatch = useDispatch();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [listOUser, setListOfUser] = useState([]);
  const [actionRows, setActionRows] = useState();
  const [loading, setLoading] = useState(false);
  const [spinLoading, setSpinLoading] = useState(false);
  const [orgTreeData, setorgTreeData] = useState([]);
  const [searchParams, setsearchParams] = useState({});
  const [pageSize, setpageSize] = useState(5);
  const [pageIndex, setpageIndex] = useState(1);
  const [total, settotal] = useState(0);

  // useImperativeHandle(ref, () => ({
  //   handleSubmit,
  // }));
  useEffect(() => {
    initComeUsers();
    return () => {};
  }, [selectUsers]);

  useEffect(() => {
    getOrgTree();
    return () => {};
  }, []);

  useEffect(() => {
    getUserList();
    return () => {};
  }, [pageSize, pageIndex]);

  const getOrgTree = () => {
    setSpinLoading(true);
    dispatch({
      type: 'orgManageModel/getOrgRootTree',
    }).then((data) => {
      setorgTreeData(data?.map((d) => ({ ...d, isLeaf: !d.hasChild })));
      setSpinLoading(false);
    });
  };

  const initComeUsers = () => {
    const forUsers = selectUsers.map((d) => ({ ...d, userName: d.username, orgs: d.orgName }));
    setActionRows(forUsers || []);
    setListOfUser(forUsers || []);
    setSelectedRowKeys(forUsers?.map((d) => d.userAccount) || []);
  };

  const onSearchTable = () => {
    getUserList();
  };

  const getUserList = () => {
    if (!searchParams.orgIdList && !searchParams.userSearchKey && searchParams.orgIdList !== 0) {
      initComeUsers();
      return;
    }
    const param = {};
    if (searchParams.orgIdList || searchParams.orgIdList === 0)
      param.orgIdList = [searchParams.orgIdList];
    if (searchParams.userSearchKey) param.userSearchKey = searchParams.userSearchKey;
    setLoading(true);
    dispatch({
      type: 'commonRoleManageModel/getUserList',
      payload: {
        pageIndex,
        pageSize,
        appCode: appCodeOfSelect,
        ...param,
      },
    }).then((res) => {
      const { code, message: errMsg, data } = res;
      if (code === 0) {
        setListOfUser(data?.dataList?.map((d) => ({ ...d, userId: d.id })));
        settotal(data?.total);
      } else {
        message.error(errMsg);
      }
      setLoading(false);
    });
  };

  const onLoadData = ({ key, children }) => {
    if (children) {
      return;
    }
    return dispatch({
      type: 'commonRoleManageModel/getChildOrgListByParentId',
      payload: { parentId: key },
    }).then((res) => {
      const { code, message: errMsg, data } = res;
      if (code === 0) {
        setorgTreeData((origin) =>
          updateTreeData(
            origin,
            key,
            data?.map((d) => ({
              ...d,
              // key: d.id,
              value: d.id,
              title: d.orgName,
              isLeaf: !d.hasChild,
            })),
          ),
        );
      } else {
        message.error(errMsg);
      }
    });
  };

  const updateTreeData = (list, key, children) => {
    return list.map((node) => {
      if (node.key === key) {
        return { ...node, children };
      }

      if (node.children) {
        return { ...node, children: updateTreeData(node.children, key, children) };
      }

      return node;
    });
  };

  const handleOk = () => {
    handOk(actionRows.map((d) => ({ ...d, username: d.userName, orgName: d.orgs })));
    // console.log(actionRows);
  };

  // 控制当前组织下用户选择项
  const onChange = (rowKeys, rows) => {
    setSelectedRowKeys(rowKeys);
  };

  // 编辑整体用户选择的增删
  const onSelectChange = (record, selected) => {
    if (selected) {
      if (!actionRows.find((d) => d.userId === record.userId)) {
        setActionRows(actionRows.concat([record]));
      }
    } else {
      setActionRows(actionRows.filter((d) => d.userId !== record.userId));
    }
  };
  // 编辑整体用户选择的增删
  const onSelectAll = (selected, selectedRows) => {
    console.log(selectedRows)
    if (selected) {
      const newRows = [];
      selectedRows.filter(Boolean).map((row) => {
        if (!actionRows.find((d) => d.userId === row.userId)) {
          newRows.push(row);
        }
      });
      setActionRows(actionRows.concat([...newRows]));
    } else {
      let newRows = [];
      newRows = actionRows.filter((d) => !listOUser.filter(Boolean).find(row => d.userId === row.userId));
      // selectedRows.filter(Boolean).map((row) => {
      //   if (!actionRows.find((d) => d.userId === row.userId)) {
      //     newRows = actionRows.filter((d) => d.userId !== row.userId);
      //   }
      // });
      setActionRows(newRows);
    }
  };
  // 树节点选中项变更事件 key:resourceId
  const onOrgTreeSelect = (selectedKeys, e) => {
    if (selectedKeys.length === 0) {
      // 无选中节点
      setListOfUser([]);
      return;
    }
    getUserList(selectedKeys);
    setSelectedRowKeys(actionRows.map((d) => d.userAccount));
  };

  // const onUserSearch = () => {
  //   setLoading(true);
  //   dispatch({
  //     type: 'commonRoleManageModel/getUserList',
  //     payload: { pageIndex: 1, pageSize: 10000, userAccount },
  //   }).then((res) => {
  //     const { code, message: errMsg, data } = res;
  //     if (code === 0) {
  //       setListOfUser(data?.dataList?.map((d) => ({ ...d, userId: d.id })));
  //     } else {
  //       message.error(errMsg);
  //     }
  //     setLoading(false);
  //   });
  // };

  const rowSelection = {
    selectedRowKeys,
    onChange,
    onSelect: onSelectChange,
    onSelectAll,
  };

  const handleTableChange = (pagination, filters, sorter) => {
    setpageSize(pagination.pageSize);
    setpageIndex(pagination.current);
  };

  return (
    <Modal
      width={700}
      title="选择用户"
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <div className={styles.root}>
        <Row gutter={18}>
          <Col>
            <Input
              placeholder="账号/姓名/工号/"
              allowClear
              onChange={(e) => setsearchParams({ ...searchParams, userSearchKey: e.target.value })}
            />
          </Col>
          <Col>
            {/* <TreeSelect
              allowClear
              style={{ width: 150 }}
              treeDataSimpleMode
              placeholder="请选择"
              loadData={onLoadData}
              loading={spinLoading}
              // onSelect={onOrgTreeSelect}
              onChange={(value) => setsearchParams({ ...searchParams, orgIdList: value })}
            /> */}
            <OrgTreeSelect
              allowClear
              style={{ width: 150 }}
              placeholder="请选择"
              dropdownMatchSelectWidth={false}
              dropdownStyle={{ maxWidth: 400 }}
              onSelect={(value) => setsearchParams({ ...searchParams, orgIdList: value })}
            />
          </Col>
          <Col>
            <Button type="primary" onClick={() => onSearchTable()}>
              搜索
            </Button>
          </Col>
        </Row>
        <div className={styles.section}>
          {/* <div style={{ width: 150, display: 'flex', flexFlow: 'column' }}>
            <div>组织信息</div>
            <Tree
              loadData={onLoadData}
              loading={spinLoading}
              onSelect={onOrgTreeSelect}
              treeData={orgTreeData}
              className={styles.orgTree}
            />
          </div> */}
          <div style={{ flex: 1 }}>
            <div>用户信息</div>
            {/* <div className={styles.menuTitleWrapper}>
              <Input
                placeholder="请输入用户信息"
                value={userAccount}
                onChange={(e) => setUserAccount(e.target.value)}
                style={{ marginRight: '20px' }}
              />
              <Button onClick={() => onUserSearch()}>查询</Button>
            </div> */}
            <div className={styles.menuTable}>
              <Table
                rowSelection={rowSelection}
                rowKey="userAccount"
                columns={columns}
                dataSource={listOUser}
                pagination={{
                  current: pageIndex,
                  pageSize,
                  total,
                }}
                scroll={{ y: 260 }}
                onChange={handleTableChange}
                loading={loading}
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default connect((state) => state)(UsersSelect);
